package com.atguigu.tingshu.search.receiver;

import com.atguigu.tingshu.common.rabbit.constant.MqConst;
import com.atguigu.tingshu.search.service.SearchService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;


@Component
@Slf4j
public class SearchReceiver {

    @Autowired
    private SearchService searchService;

    /**
     * 监听专辑上架
     * @param albumId
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConst.QUEUE_ALBUM_UPPER, durable = "true", autoDelete = "false"),
            exchange = @Exchange(value = MqConst.EXCHANGE_ALBUM),
            key = MqConst.ROUTING_ALBUM_UPPER
    )
    )
    public void albumUpper(Long albumId, Message message, Channel channel) {
        //  监听专辑上架;
        System.out.println("更新专辑：" + albumId);
        try {
            if (null != albumId){
                searchService.upperAlbum(albumId);
            }
        } catch (Exception e) {
            log.error(e.getMessage(),e);
        }
        //  手动签收;
        try {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 监听专辑下架
     * @param albumId
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConst.QUEUE_ALBUM_LOWER, durable = "true", autoDelete = "false"),
            exchange = @Exchange(value = MqConst.EXCHANGE_ALBUM),
            key = MqConst.ROUTING_ALBUM_LOWER
    )
    )
    public void albumLower(Long albumId, Message message, Channel channel) {
        //  监听专辑下架;
        System.out.println("更新专辑：" + albumId);
        try {
            if (null != albumId){
                searchService.lowerAlbum(albumId);
            }
        } catch (Exception e) {
            log.error(e.getMessage(),e);
        }
        //  手动签收;
        try {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
